import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/user_total.dart';
import 'package:mall/core/providers/pages/mine/store_apply_std_model.dart';
import 'package:mall/core/providers/pages/mine/store_apply_query_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mall/screens/address/address_region_page.dart';
import 'package:provider/provider.dart';

/// 店铺申领
class StoreApplyPage extends StatelessWidget {
  static const routeName = '/StoreApplyPage';
  final UserTotal args;

  StoreApplyPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => StoreApplyQueryModel(Provider.of(context, listen: false)),
      child: Scaffold(
        appBar: AppBar(
          title: Text('店铺申领'),
        ),
        body: Consumer<StoreApplyQueryModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Center(
                  child: CircularProgressIndicator(),
                );
              case ViewState.error:
                return Center(
                  child: Text(model.errorMessage),
                );
              case ViewState.success:
                return Provider.value(
                  value: args,
                  child: _SuccessWidget(),
                );
              default:
                return Container();
            }
          },
        ),
      ),
    );
  }
}

/// 查询成功，显示编辑内容
class _SuccessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => StoreApplyModel(Provider.of(context, listen: false)),
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            _ListAndStatusWidget(),
            SizedBox(height: 40),
            _BottomConfirmWidget(),
          ],
        ),
      ),
    );
  }
}

/// 编辑列表和状态
class _ListAndStatusWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 根据imageFileMap字段，解析出需要显示和隐藏等图片文件字段项
    UserTotal userTotal = Provider.of(context, listen: false);

    String imageFileMapRadix = userTotal.imageFileMap.toRadixString(2);
    debugPrint('imageFileMapRadix = $imageFileMapRadix');

    // 1、默认都显示
    bool showLogo = true;
    bool showIdCard = true;
    bool showLicense = true;

    // 2、如果第一次，也就是storeId == null，就判断imageFileMap标记
    if (userTotal.storeId == null || userTotal.storeId <= 0) {
      var map = userTotal.imageFileMap;
      showLogo = (map & 0x1 > 0);
      showIdCard = (map & 0x10 > 0);
      showLicense = (map & 0x100 > 0);
    }

    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    return Stack(
      alignment: Alignment.bottomRight,
      children: [
        Column(
          children: [
            _ItemNameWidget(),
            if (showLogo) ...[
              Divider(height: 1, indent: 16),
              _ItemLogoWidget(),
            ],
            if (showIdCard) ...[
              Divider(height: 1, indent: 16),
              _ItemIdCardWidget(),
            ],
            if (showLicense) ...[
              Divider(height: 1, indent: 16),
              _ItemLicenseWidget(),
            ],
            Divider(height: 1, indent: 16),
            _CountyItemWidget(),
            if (storeApplyQueryModel.data.auditStatus == 'AUDIT_FAIL') ...[
              Divider(height: 1, indent: 16),
              _ItemAuditNoteWidget(),
            ],
          ],
        ),
        if (storeApplyQueryModel.data.auditStatus == 'AUDITING')
          Container(
            margin: EdgeInsets.all(16),
            child: Image.asset('assets/images/withdraw/img_auditing.png', height: 168),
          ),
      ],
    );
  }
}

/// 店铺名称
class _ItemNameWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    StoreApplyModel storeApplyModel = Provider.of(context, listen: false);
    return Container(
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      padding: EdgeInsets.symmetric(horizontal: 16),
      height: 50,
      child: TextFormField(
        initialValue: storeApplyQueryModel.data.storeName ?? '',
        decoration: InputDecoration(
          hintText: '请输入店铺名称',
          border: InputBorder.none,
        ),
        onChanged: (value) {
          storeApplyModel.name = value;
        },
      ),
    );
  }
}

/// 店铺LOGO
class _ItemLogoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    StoreApplyModel storeApplyModel = Provider.of(context);
    return InkWell(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        height: 50,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text('店铺logo'),
            ),
            storeApplyModel.logo == null
                ? CachedNetworkImage(
                    imageUrl: storeApplyQueryModel.data.logo ?? '',
                    height: 40,
                  )
                : Image.file(
                    storeApplyModel.logo,
                    height: 40,
                  ),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colors.grey,
            )
          ],
        ),
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) async {
    var result = await showModalBottomSheet<File>(
      context: context,
      builder: (context) {
        return _BottomSheetWidget();
      },
    );
    debugPrint('logo result = $result');
    if (result != null) {
      StoreApplyModel model = Provider.of(context, listen: false);
      model.logo = result;
    }
  }
}

/// 身份证
class _ItemIdCardWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    StoreApplyModel storeApplyModel = Provider.of(context);
    return InkWell(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        height: 50,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text('身份证'),
            ),
            storeApplyModel.idCard == null
                ? CachedNetworkImage(
                    imageUrl: storeApplyQueryModel.data.idCard ?? '',
                    height: 40,
                  )
                : Image.file(
                    storeApplyModel.idCard,
                    height: 40,
                  ),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colors.grey,
            )
          ],
        ),
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) async {
    var result = await showModalBottomSheet<File>(
      context: context,
      builder: (context) {
        return _BottomSheetWidget();
      },
    );
    debugPrint('idCard result = $result');
    if (result != null) {
      StoreApplyModel model = Provider.of(context, listen: false);
      model.idCard = result;
    }
  }
}

/// 营业执照
class _ItemLicenseWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    StoreApplyModel storeApplyModel = Provider.of(context);
    return InkWell(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        height: 50,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text('营业执照'),
            ),
            storeApplyModel.license == null
                ? CachedNetworkImage(
                    imageUrl: storeApplyQueryModel.data.license ?? '',
                    height: 40,
                  )
                : Image.file(
                    storeApplyModel.license,
                    height: 40,
                  ),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colors.grey,
            )
          ],
        ),
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) async {
    var result = await showModalBottomSheet<File>(
      context: context,
      builder: (context) {
        return _BottomSheetWidget();
      },
    );
    debugPrint('license result = $result');
    if (result != null) {
      StoreApplyModel model = Provider.of(context, listen: false);
      model.license = result;
    }
  }
}

/// 行政区县
class _CountyItemWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    StoreApplyModel storeApplyModel = Provider.of(context);
    return InkWell(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        height: 50,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text('行政区县'),
            ),
            Text(storeApplyModel.county?.value ?? storeApplyQueryModel.data?.provCityCounty ?? ''),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colors.grey,
            )
          ],
        ),
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) async {
    final result = await Navigator.of(context).pushNamed(
      AddressRegionPage.routeName,
      arguments: AddressRegionArgs(0, null),
    );
    debugPrint('result = $result');
    if (result != null && result is MapEntry<String, dynamic>) {
      final model = context.read<StoreApplyModel>();
      model.county = result;
    }
  }
}

/// 审核备注
class _ItemAuditNoteWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      height: 50,
      child: Row(
        children: <Widget>[
          Image.asset(
            'assets/images/withdraw/img_audit_fail.png',
            height: 24,
            color: Colors.red,
          ),
          SizedBox(width: 8),
          Text(
            '${storeApplyQueryModel.data.auditNote ?? '--'}',
            style: TextStyle(color: Colors.red),
          )
        ],
      ),
    );
  }
}

/// 选择图片的方式
class _BottomSheetWidget extends StatelessWidget {
  final ImagePicker _picker = ImagePicker();
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          ListTile(
            title: Text('拍照'),
            onTap: () {
              _onItemClicked(context, ImageSource.camera);
            },
          ),
          ListTile(
            title: Text('从相册选择'),
            onTap: () {
              _onItemClicked(context, ImageSource.gallery);
            },
          ),
        ],
      ),
    );
  }

  void _onItemClicked(BuildContext context, ImageSource source) async {
    final file = await _picker.getImage(
      source: source,
      maxWidth: 256,
      maxHeight: 256,
    );
    Navigator.of(context).pop(File(file.path));
  }
}

/// 底部确定按钮
class _BottomConfirmWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.maxFinite,
      margin: EdgeInsets.all(16),
      child: Consumer<StoreApplyModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return RaisedButton(
                onPressed: null,
                child: SizedBox(
                  child: CircularProgressIndicator(),
                ),
              );
            default:
              return RaisedButton(
                onPressed: () {
                  _onConfirmClicked(context);
                },
                child: Text(
                  '确定',
                  style: TextStyle(fontSize: 18),
                ),
              );
          }
        },
      ),
    );
  }

  void _onConfirmClicked(BuildContext context) async {
    StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
    StoreApplyModel storeApplyModel = Provider.of(context, listen: false);
    var viewState = await storeApplyModel.storeApplyStd(storeApplyQueryModel.data);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(storeApplyModel.errorMessage);
        break;
      default:
        EasyLoading.showToast('申请成功');
        if (storeApplyModel.data.auditStatus == 'AUDITING') {
          // 审核中，替换之前查询的data数据，刷新UI
          StoreApplyQueryModel storeApplyQueryModel = Provider.of(context, listen: false);
          storeApplyQueryModel.data = storeApplyModel.data;
        } else if (storeApplyModel.data.auditStatus == 'AUDIT_SUCCESS') {
          // 审核成功，返回数据，直接跳转到管理页面
          Navigator.of(context).pop(storeApplyModel.data);
        }
        break;
    }
  }
}
